<?php

namespace app\modules\setting\models;

use Yii;

/**
 * This is the model class for table "rbac_user_permissions".
 *
 * @property int $user_permission_id
 * @property int $user_id
 * @property int $role_id
 * @property string $crt_name
 * @property string $crt_time
 * @property int|null $deleted_at
 */
class UserPermissions extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'rbac_user_permissions';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_id', 'role_id', 'crt_time'], 'required'],
            [['user_id', 'role_id', 'deleted_at'], 'integer'],
            [['crt_time'], 'safe'],
            [['crt_name'], 'string', 'max' => 50],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'user_id' => '用户ID',
            'role_id' => '角色',
            'crt_name' => '创建人',
            'crt_time' => '创建时间',
        ];
    }


    /**
     * @return \yii\db\ActiveQuery
     * @author sally
     * @date   2020-07-06
     */
    public function getRole()
    {
        return $this->hasOne(RolesLut::className(), ['role_id' => 'role_id']);
    }


    /**
     * @param $user_id
     *
     * @return array
     * @author sally
     * @date   2020-07-06
     */
    static public function getPermissions($user_id)
    {
        $permissions = (new \yii\db\Query())
            ->select(['rp.permission_id', 'permission.permission_name'])
            ->from('rbac_user_permissions as up')
            ->leftJoin('rbac_role_permissions as rp', 'rp.role_id = up.role_id')
            ->leftJoin('rbac_permissions_lut as permission', 'permission.permission_id = rp.permission_id')
            ->where(['up.user_id' => $user_id, 'up.delete_at' => 0])
            ->all();

        return $permissions;
    }


    /**
     * @param $user_id
     * @param $role_ids
     *
     * @return bool
     * @throws \yii\db\Exception
     * @author sally
     * @date   2020-07-06
     */
    static public function saveUserRoles($user_id, $role_ids)
    {
        // set old roles to delete
        UserPermissions::updateAll(['delete_at' => strtotime(date("Y-m-d H:i:s"))], ['user_id' => $user_id, 'delete_at' => 0]);

        $insert_data = [];
        $crt_name = Yii::$app->user->identity->username;
        $crs_time = date('Y-m-d H:i:s');
foreach ($role_ids as $role_id) {
            $insert_data[] = [$user_id, $role_id, $crt_name, $crs_time];
        }

        // add new roles
        Yii::$app->db->createCommand()->batchInsert('rbac_user_permissions', ['user_id', 'role_id', 'crt_name', 'crt_time'], $insert_data)->execute();

        return true;
    }
}
